package com.yaodian100.ec.generatepage.web;

import java.awt.Image;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import javax.imageio.ImageIO;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.FastDateFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import com.yaodian100.core.common.service.DomainService;
import com.yaodian100.core.common.utils.DateUtil;
import com.yaodian100.core.menu.entity.Menu;
import com.yaodian100.ec.common.EcConstant;
import com.yaodian100.ec.generate.entity.EventImage;
import com.yaodian100.ec.generate.entity.GenerateAdvertise;
import com.yaodian100.ec.generate.entity.GenerateContent;
import com.yaodian100.ec.generate.entity.GeneratePosition;
import com.yaodian100.ec.generate.service.GenerateService;

public class IdxSpecialActAction extends ActionSupport implements Preparable {
	
	private static final long serialVersionUID = 5234641235999600390L;
	
	private final Logger logger = LoggerFactory.getLogger(IdxSpecialActAction.class);
	
	private GenerateService generateService;
	
	private DomainService<Menu> menuService;
	
	private GenerateAdvertise advertise;
	
	private GeneratePosition position;
	
	private GenerateContent content;
	
	private StringBuilder contents;
	
	private EventImage eventImage;
	
	/**
	 * 广告版面位置选单
	 */
	private Menu advPositionMenu;
	
	/**
	 * 广告ID
	 */
	private String advId;
	
	/**
	 * 广告状态
	 * 
	 * 00: 草稿, 10: 发送, 20: 放送中, 80: 过期, 90: 占停
	 */
	private String advStatus;
	
	/**
	 * OPTION CODE
	 */
	private String advType = "IDX_SPECIAL_ACT";
	
	/**
	 * 广告名称
	 */
	private String advName;
	
	/**
	 * 广告位置
	 */
	private String advTarget;
	
	/**
	 * 广告起始日
	 */
	private String startDate;
	
	/**
	 * 广告结束日
	 */
	private String endDate;

	/**
	 * 广告起始时间
	 */
	private String startTime;

	/**
	 * 广告结束时间
	 */
	private String endTime;
	
	/**
	 * 主题图片-图档
	 */
	private File mainImg;
	
	/**
	 * 主题图片-图档名称
	 */
	private String mainImgName;
	
	/**
	 * 主题图片-图档资料夹
	 */
	private String mainImgFolder;
	
	/**
	 * 主题图片-连结
	 */
	private String mainImgLink;
	
	/**
	 * 主题图片-广告代码
	 */
	private String mainAdWord;
	
	/**
	 * 文字标题
	 */
	private String[] textTitle;
	
	/**
	 * 文字点击连结
	 */
	private String[] textLink;
	
	/**
	 * 文字广告代码
	 */
	private String[] textAdWord;
	
	/**
	 * 商品编号
	 */
	private String[] prodId;
	
	/**
	 * 商品小标
	 */
	private String[] brief;
	
	/**
	 * 商品名称
	 */
	private String[] prodName;
	
	/**
	 * 商品-广告代码
	 */
	private String[] adWord;
	
	private String createUser;
	private Date createDate;
	private String modifyUser;
	private Date modifyDate;
	private boolean doClone;
	private String from;
	
	/**
	 * 日期格式化
	 */
	protected final DateFormat PATTERN_DATE_FORMAT = new SimpleDateFormat(EcConstant.PATTERN_TIMESTAMP);
	
	private final int TEXT_SIZE = 4;
	
	private final int PROD_SIZE = 6;
	
	protected final String lineBreak = "\n";
	
	/**
	 * 新增首页活动特辑广告
	 * 
	 * @return
	 */
	public String addIdxSpecialAct() {
		advId = "";
		
		if( StringUtils.equalsIgnoreCase(from, "PCL") ) {
			advType = "PCL_SPECIAL_ACT";
		} else {
			advType = "IDX_SPECIAL_ACT";
		}
		
		initVariables();
		return "editIdxSpecialAct";
	}
	
	/**
	 * 儲存首页活动特辑广告
	 * 
	 * @return
	 * @throws Exception
	 */
	public String saveIdxSpecialAct() throws Exception {
		boolean boo = false;
		
		double imgSize = 25.0;
		int imgWidth = 455;
		int imgHeight = 180;
		int error_flag = 0;
		
		if(idxSpecialActValidate()) {
			contents = new StringBuilder("");
			
			if (GenerateHelper.mkDir(advType)) {
				if (StringUtils.isBlank(advId) && !doClone) { // insert
					if(validateFile(mainImg, "mainImg", "主题图片", imgSize, imgWidth, imgHeight)) {
						contents.append(saveImgFile(mainImg, mainImgName, advType, "mainImgName", "mainImgFolder"));
					} else {
						contents.append("mainImgName=").append(lineBreak);
						contents.append("mainImgFolder=").append(lineBreak);
						error_flag++;
					}
				} else { // update
					if(mainImg == null) {
						contents.append("mainImgName=").append(mainImgName).append(lineBreak);
						contents.append("mainImgFolder=").append(mainImgFolder).append(lineBreak);
					} else {
						if(validateFile(mainImg, "mainImg", "主题图片", imgSize, imgWidth, imgHeight)) {
							contents.append(saveImgFile(mainImg, mainImgName, advType, "mainImgName", "mainImgFolder"));
						} else {
							contents.append("mainImgName=").append(mainImgName).append(lineBreak);
							contents.append("mainImgFolder=").append(mainImgFolder).append(lineBreak);
							error_flag++;
						}
					}
				}
			}
			
			// 1. 广告位置
			//contents.append("advPosition=").append(advPosition).append(lineBreak);
			
			// 2. 图片连结
			contents.append("mainImgLink=").append(mainImgLink).append(lineBreak);
			
			// 3. 主题图片广告代码
			if(StringUtils.isNotBlank(mainAdWord))
				contents.append("mainAdWord=").append(mainAdWord).append(lineBreak);
			
			// 4. 文字标题
			for(int i = 0; i < TEXT_SIZE; i++) { 
				int x = i + 1;
				contents.append("textTitle"+x+"=").append(textTitle[i]).append("\n")
					.append("textLink"+x+"=").append(textLink[i]).append("\n");
				if(StringUtils.isNotBlank(textAdWord[i]))
					contents.append("textAdWord"+x+"=").append(textAdWord[i]).append("\n");
			}
			
			// 5. 商品
			for(int i = 0; i < PROD_SIZE; i++) { 
				int x = i + 1;
				contents.append("prodId"+x+"=").append(prodId[i]).append("\n")
					.append("brief"+x+"=").append(brief[i]).append("\n")
					.append("prodName"+x+"=").append(prodName[i]).append("\n");
				
				if(StringUtils.isNotBlank(adWord[i]))
					contents.append("adWord"+x+"=").append(adWord[i]).append("\n");
			}
			
			if(StringUtils.isBlank(advId)) {
				advertise = new GenerateAdvertise();
				position = new GeneratePosition();
				content = new GenerateContent();
			} else {
				advertise = generateService.get(Long.parseLong(advId));
				position = generateService.getGeneratePositionByAdvId(Long.parseLong(advId)).get(0);
				content = generateService.getGenerateContentByAdvId(Long.parseLong(advId)).get(0);
			}
			// set advertise
			advertise.setAdvType(advType);
			advertise.setAdvName(advName.trim());
			advertise.setStartDate(PATTERN_DATE_FORMAT.parse(startDate + " " + startTime + ":00"));
			advertise.setEndDate(PATTERN_DATE_FORMAT.parse(endDate + " " + endTime + ":59"));
			advertise.setAdvStatus(advStatus);
			position.setAdvTarget(advTarget);
			content.setContents(contents.toString());
			
			if (error_flag == 0) {
				if (StringUtils.countMatches(content.getContents(), "prodId") == PROD_SIZE) {
					if (StringUtils.isBlank(advId))
						boo = generateService.saveGenerateCombine(advertise, position, content);
					else
						boo = generateService.updateGenerateCombine(advertise, position, content);
				}
			}
			contents.setLength(0);
			
			// 存檔後執行产档逻辑
			if( StringUtils.equalsIgnoreCase(from, "PCL") ) {
				generateService.generaterPclSpecialAct();
			} else {
				generateService.generaterIdxSpecialAct();
			}
			
			if(boo) {
				advId = advertise.getId().toString();
				if(error_flag == 0)
					addActionMessage("储存成功");
				return editIdxSpecialAct();
			}
		}
		
		return "editIdxSpecialAct";
	}
	
	/**
	 * 编辑首页活动特辑广告
	 * 
	 * @return
	 * @throws IOException 
	 */
	public String editIdxSpecialAct() throws IOException {
		initVariables();
		
		if(!StringUtils.isBlank(advId)) {
			advertise = generateService.get(Long.parseLong(advId));
			position = generateService.getGeneratePositionByAdvId(Long.parseLong(advId)).get(0);
			content = generateService.getGenerateContentByAdvId(Long.parseLong(advId)).get(0);
			
			advStatus = advertise.getAdvStatus();
			advType = advertise.getAdvType();
			advName = advertise.getAdvName();
			
			advTarget = position.getAdvTarget();
			
			startDate = FastDateFormat.getInstance(EcConstant.PATTERN_DATE).format(advertise.getStartDate());
			endDate = FastDateFormat.getInstance(EcConstant.PATTERN_DATE).format(advertise.getEndDate());
			startTime = FastDateFormat.getInstance("HH:mm").format(advertise.getStartDate());
			endTime = FastDateFormat.getInstance("HH:mm").format(advertise.getEndDate());
			
			createUser = advertise.getCreateUser();
			createDate = advertise.getCreateDate();
			modifyUser = advertise.getModifyUser();
			modifyDate = advertise.getModifyDate();
			
			readPropertise(content);
		}
		
		return "editIdxSpecialAct";
	}
	
	public String cloneIdxSpecialAct() throws IOException {
		initVariables();
		doClone = true;
		
		if(!StringUtils.isBlank(advId)) {
			advertise = generateService.get(Long.parseLong(advId));
			position = generateService.getGeneratePositionByAdvId(Long.parseLong(advId)).get(0);
			content = generateService.getGenerateContentByAdvId(Long.parseLong(advId)).get(0);
			
			GenerateAdvertise tmp_advertise = new GenerateAdvertise();
			BeanUtils.copyProperties(advertise, tmp_advertise, new String[] {"id", "createDate", "createUser", "modifyUser", "modifyDate"});
			advertise = tmp_advertise;
			
			GeneratePosition tmp_position = new GeneratePosition();
			BeanUtils.copyProperties(position, tmp_position, new String[] {"id", "advId", "createDate", "createUser", "modifyUser", "modifyDate"});
			position = tmp_position;
			
			GenerateContent tmp_content = new GenerateContent();
			BeanUtils.copyProperties(content, tmp_content, new String[] {"id", "advId", "createDate", "createUser", "modifyUser", "modifyDate"});
			content = tmp_content;
			
			advStatus = advertise.getAdvStatus();
			advType = advertise.getAdvType();
			advName = advertise.getAdvName();
			
			advTarget = position.getAdvTarget();
			
			startDate = FastDateFormat.getInstance(EcConstant.PATTERN_DATE).format(advertise.getStartDate());
			endDate = FastDateFormat.getInstance(EcConstant.PATTERN_DATE).format(advertise.getEndDate());
			startTime = FastDateFormat.getInstance("HH:mm").format(advertise.getStartDate());
			endTime = FastDateFormat.getInstance("HH:mm").format(advertise.getEndDate());
			
			createUser = advertise.getCreateUser();
			createDate = advertise.getCreateDate();
			modifyUser = advertise.getModifyUser();
			modifyDate = advertise.getModifyDate();
			
			readPropertise(content);
			
			advId = null;
		}
		
		return "editIdxSpecialAct";
	}
	
	void readPropertise(GenerateContent content) throws IOException {
		Properties prop = new Properties();
		Reader reader = new StringReader(content.getContents());
		prop.load(reader);
		reader.close();
		
		// 1. 广告位置
		//advPosition = StringUtils.defaultString(prop.get("advPosition").toString(), "");
		
		// 2. 图片
		mainImgName = StringUtils.defaultString(prop.get("mainImgName").toString(), "");
		mainImgFolder = StringUtils.defaultString(prop.get("mainImgFolder").toString(), "");
		mainImgLink = StringUtils.defaultString(prop.get("mainImgLink").toString(), "");
		if(prop.containsKey("mainAdWord")) 
			mainAdWord = StringUtils.defaultString(prop.get("mainAdWord").toString(), "");
		
		// 4. 文字标题
		for(int i = 0; i < TEXT_SIZE; i++) {
			int x = i + 1;
			textTitle[i] = StringUtils.defaultString(prop.get("textTitle" + x).toString(), "");
			textLink[i] = StringUtils.defaultString(prop.get("textLink" + x).toString(), "");
			if(prop.containsKey("textAdWord" + x)) 
				textAdWord[i] = StringUtils.defaultString(prop.get("textAdWord" + x).toString(), "");
			else 
				textAdWord[i] = "";
		}
		
		// 5. 商品
		for(int i = 0; i < PROD_SIZE; i++) {
			int x = i + 1;
			prodId[i] = StringUtils.defaultString(prop.get("prodId" + x).toString(), "");
			prodName[i] = StringUtils.defaultString(prop.get("prodName" + x).toString(), "");
			brief[i] = StringUtils.defaultString(prop.get("brief" + x).toString(), "");
			if(prop.containsKey("adWord" + x)) 
				adWord[i] = StringUtils.defaultString(prop.get("adWord" + x).toString(), "");
			else 
				adWord[i] = "";
		}
		
	}
	
	/**
	 * 初始化变数值
	 */
	void initVariables() {
		advertise = new GenerateAdvertise();
		position = new GeneratePosition();
		content = new GenerateContent();
		
		mainImg = null;
		mainImgFolder = "";
		mainImgLink = "";
		mainImgName = "";
		mainAdWord = "";
		
		textTitle = new String[TEXT_SIZE];
		textLink = new String[TEXT_SIZE];
		textAdWord = new String[TEXT_SIZE];
		prodId = new String[PROD_SIZE];
		prodName = new String[PROD_SIZE];
		brief = new String[PROD_SIZE];
		adWord = new String[PROD_SIZE];
		
		startDate = "";
		endDate = "";
		startTime = "";
		endTime = "";
		advName = "";
		
		doClone = false;
	}
	
	/**
	 * 储存图片
	 * 
	 * @param imgFile
	 * @param fileName
	 * @param advType
	 * @param imgName
	 * @param imgFolder
	 * @return
	 * @throws Exception
	 */
	String saveImgFile(File imgFile, String fileName, String advType, String imgName, String imgFolder) throws Exception {
		StringBuffer sb = new StringBuffer();
		try {
			String today = FastDateFormat.getInstance(EcConstant.DEFAULT_PATTERN_DATE).format(DateUtil.getToday().getTime());
			eventImage = new EventImage();
			eventImage.setImgType(fileName.substring(fileName.lastIndexOf("."), fileName.length()));
			eventImage = generateService.saveEventImage(eventImage);
			boolean result = GenerateHelper.uploadImage(eventImage, imgFile, advType);
			if (result) {
				sb.append(imgName + "=").append(eventImage.getUuid()).append(eventImage.getImgType()).append(lineBreak);
				sb.append(imgFolder + "=").append(today).append(lineBreak);
			} else {
				sb.append(imgName + "=").append(lineBreak);
				sb.append(imgFolder + "=").append(lineBreak);
			}
		} catch (Exception e) {
			logger.info("exception :{}", e.getMessage());
		}
		return sb.toString();
	}
	
	/**
	 * 检合图片
	 * 
	 * @param imgFile
	 * @param fieldName
	 * @param fieldNameMsg
	 * @param fileName
	 * @param fileSize
	 * @param fileWidth
	 * @param fileHeight
	 * @return
	 * @throws IOException
	 */
	boolean validateFile(File imgFile, String fieldName, String fieldNameMsg, double fileSize,
			int fileWidth, int fileHeight) throws IOException {
		int error_size = 0;
		if (null != imgFile) {
			if ((imgFile.length() / 1024) > fileSize) {
				addFieldError(fieldName, fieldNameMsg + "檔案尺寸不符");
				error_size++;
			}
			
			Image image = ImageIO.read(imgFile);
			if(image != null) {
				if (image.getHeight(null) > fileHeight || image.getWidth(null) > fileWidth) {
					addFieldError(fieldName, fieldNameMsg + "檔案长度/宽度不符");
					error_size++;
				}
			} else 
				error_size++;
			
			if (error_size > 0)
				return false;
			else
				return true;
		} else
			return false;
	}
	
	/**
	 * 必填栏位验证
	 * 
	 * @return
	 */
	boolean idxSpecialActValidate() {
		if(StringUtils.isBlank(advName)) {
			addFieldError("advName", "请输入广告名称");
		}
		
		if(StringUtils.isBlank(advTarget)) {
			addFieldError("advTarget", "请输入广告位置");
		}
		
		if(StringUtils.isBlank(startDate)) {
			addFieldError("startDate", "请输入起始日期");
		}
		
		if(StringUtils.isBlank(endDate)) {
			addFieldError("endDate", "请输入结束日期");
		}
		
		if(textTitle != null && textLink != null) {
			for(int i = 0; i < TEXT_SIZE; i++) {
				int x = i + 1;
				if(StringUtils.isBlank(textTitle[i])) {
					addFieldError("textTitle" + x, "請輸入文字标题" + x);
				}
				if(StringUtils.isBlank(textLink[i])) {
					addFieldError("textLink" + x, "请输入文字标题" + x + "点击连结");
				}
			}
		} else {
			for(int i = 1; i <= TEXT_SIZE; i++) {
				addFieldError("textTitle" + i, "請輸入文字标题" + i);
				addFieldError("textLink" + i, "请输入文字标题" + i + "点击连结");
			}
		}
		
		if(prodId != null && brief != null && prodName != null) {
			for(int i = 0; i < PROD_SIZE; i++) {
				int x = i + 1;
				if(StringUtils.isBlank(prodId[i])) {
					addFieldError("prodId" + x, "請輸入商品编号" + x);
				} else if(!generateService.isProductExist(prodId[i])) {
					addFieldError("prodId" + x, "商品"+x+"可能不存在，或是已被删除，或是不在架上");
				}
				if(StringUtils.isBlank(brief[i])) {
					addFieldError("brief" + x, "请输入商品小标" + x);
				}
				if(StringUtils.isBlank(prodName[i])) {
					addFieldError("prodName" + x, "请输入商品名称" + x);
				}
			}
		} else {
			for(int i = 1; i <= PROD_SIZE; i++) {
				addFieldError("prodId" + i, "請輸入商品编号" + i);
				addFieldError("brief" + i, "请输入商品小标" + i);
				addFieldError("prodName" + i, "请输入商品名称" + i);
			}
		}
		
		if (getFieldErrors().isEmpty()) {
			return true;
		} else {
			return false;
		}
	}
	
	@Override
	public void prepare() throws Exception {
		clearErrorsAndMessages();
		
		// 取得menu
		if(advPositionMenu == null)
			advPositionMenu = menuService.get("IdxSpecialAct.advPosition");
	}
	
	// Getters & Setters
	public DomainService<Menu> getMenuService() {
		return menuService;
	}

	public void setMenuService(DomainService<Menu> menuService) {
		this.menuService = menuService;
	}

	public Menu getAdvPositionMenu() {
		return advPositionMenu;
	}

	public void setAdvPositionMenu(Menu advPositionMenu) {
		this.advPositionMenu = advPositionMenu;
	}

	public String getAdvId() {
		return advId;
	}

	public void setAdvId(String advId) {
		this.advId = advId;
	}

	public String getAdvTarget() {
		return advTarget;
	}

	public void setAdvTarget(String advTarget) {
		this.advTarget = advTarget;
	}

	public String getAdvType() {
		return advType;
	}

	public void setAdvType(String advType) {
		this.advType = advType;
	}

	public String getAdvName() {
		return advName;
	}

	public void setAdvName(String advName) {
		this.advName = advName;
	}

	public GenerateService getGenerateService() {
		return generateService;
	}

	public void setGenerateService(GenerateService generateService) {
		this.generateService = generateService;
	}

	public String getAdvStatus() {
		return advStatus;
	}

	public void setAdvStatus(String advStatus) {
		this.advStatus = advStatus;
	}

	public String getStartDate() {
		return startDate;
	}

	public void setStartDate(String startDate) {
		this.startDate = startDate;
	}

	public String getEndDate() {
		return endDate;
	}

	public void setEndDate(String endDate) {
		this.endDate = endDate;
	}

	public String getStartTime() {
		return startTime;
	}

	public void setStartTime(String startTime) {
		this.startTime = startTime;
	}

	public String getEndTime() {
		return endTime;
	}

	public void setEndTime(String endTime) {
		this.endTime = endTime;
	}

	public File getMainImg() {
		return mainImg;
	}

	public void setMainImg(File mainImg) {
		this.mainImg = mainImg;
	}

	public String getMainImgName() {
		return mainImgName;
	}

	public void setMainImgName(String mainImgName) {
		this.mainImgName = mainImgName;
	}

	public String getMainImgFolder() {
		return mainImgFolder;
	}

	public void setMainImgFolder(String mainImgFolder) {
		this.mainImgFolder = mainImgFolder;
	}

	public String getMainImgLink() {
		return mainImgLink;
	}

	public void setMainImgLink(String mainImgLink) {
		this.mainImgLink = mainImgLink;
	}

	public String getMainAdWord() {
		return mainAdWord;
	}

	public void setMainAdWord(String mainAdWord) {
		this.mainAdWord = mainAdWord;
	}

	public String[] getTextTitle() {
		return textTitle;
	}

	public void setTextTitle(String[] textTitle) {
		this.textTitle = textTitle;
	}

	public String[] getTextLink() {
		return textLink;
	}

	public void setTextLink(String[] textLink) {
		this.textLink = textLink;
	}

	public String[] getTextAdWord() {
		return textAdWord;
	}

	public void setTextAdWord(String[] textAdWord) {
		this.textAdWord = textAdWord;
	}

	public String[] getProdId() {
		return prodId;
	}

	public void setProdId(String[] prodId) {
		this.prodId = prodId;
	}

	public String[] getBrief() {
		return brief;
	}

	public void setBrief(String[] brief) {
		this.brief = brief;
	}

	public String[] getProdName() {
		return prodName;
	}

	public void setProdName(String[] prodName) {
		this.prodName = prodName;
	}

	public String[] getAdWord() {
		return adWord;
	}

	public void setAdWord(String[] adWord) {
		this.adWord = adWord;
	}

	public GenerateAdvertise getAdvertise() {
		return advertise;
	}

	public void setAdvertise(GenerateAdvertise advertise) {
		this.advertise = advertise;
	}

	public GeneratePosition getPosition() {
		return position;
	}

	public void setPosition(GeneratePosition position) {
		this.position = position;
	}

	public GenerateContent getContent() {
		return content;
	}

	public void setContent(GenerateContent content) {
		this.content = content;
	}

	public StringBuilder getContents() {
		return contents;
	}

	public void setContents(StringBuilder contents) {
		this.contents = contents;
	}

	public int getTEXT_SIZE() {
		return TEXT_SIZE;
	}

	public int getPROD_SIZE() {
		return PROD_SIZE;
	}

	public String getCreateUser() {
		return createUser;
	}

	public void setCreateUser(String createUser) {
		this.createUser = createUser;
	}

	public Date getCreateDate() {
		return createDate;
	}

	public void setCreateDate(Date createDate) {
		this.createDate = createDate;
	}

	public String getModifyUser() {
		return modifyUser;
	}

	public void setModifyUser(String modifyUser) {
		this.modifyUser = modifyUser;
	}

	public Date getModifyDate() {
		return modifyDate;
	}

	public void setModifyDate(Date modifyDate) {
		this.modifyDate = modifyDate;
	}

	public boolean isDoClone() {
		return doClone;
	}

	public void setDoClone(boolean doClone) {
		this.doClone = doClone;
	}

	public String getFrom() {
		return from;
	}

	public void setFrom(String from) {
		this.from = from;
	}

}
